package com.ly.push.service.impl;

import com.ly.push.param.WxMpProperties;
import com.ly.push.param.wx.QyWxRobot;
import com.ly.push.param.wx.WxMsgBean;
import com.ly.push.db.bean.UserArea;
import com.ly.push.db.bean.UserLog;
import com.ly.push.db.mapper.UserAreaMapper;
import com.ly.push.db.mapper.UserLogMapper;
import com.ly.push.service.WxService;
import com.ly.push.utils.QyWxUtils;
import com.ly.push.utils.TimeUtils;
import com.ly.push.utils.WxUtils;
import com.ly.push.utils.AddrUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class WxServiceImpl implements WxService {

    private Logger logger = LogManager.getLogger(WxServiceImpl.class);

    @Autowired
    private WxMpProperties wxMpProperties;
    @Autowired
    UserAreaMapper userAreaMapper;
    @Autowired
    UserLogMapper userLogMapper;
    @Autowired
    private WxUtils wxUtils ;
    @Autowired
    private AddrUtils addrUtils;
    @Autowired
    private QyWxUtils qyWxUtils;

    @Override
    public String wxCheckGet(String signature, String timestamp, String nonce, String echostr) {
        ArrayList<String> array = new ArrayList<String>();
        array.add(signature);
        array.add(timestamp);
        array.add(nonce);
        //排序
        String sortString = wxUtils.sort(wxMpProperties.getToken(), timestamp, nonce);
        //加密
        String mytoken = wxUtils.SHA1(sortString);
        //校验签名
        if (mytoken != null && mytoken != "" && mytoken.equals(signature)) {
            logger.info("签名校验通过");
            return echostr; //如果检验成功输出echostr，微信服务器接收到此输出，才会确认检验完成。
        } else {
            logger.error("签名校验失败");
            return null;
        }
    }

    //存储所有用户信息
    Map<String,Map<String,String>> mmInfo = new HashMap<>();
    //存储单个用户信息
    Map<String,String> mInfo = new HashMap<>();
    @Override
    public String wxCheckPost(WxMsgBean wxMsgBean, String signature, String timestamp, String nonce) {
        //用户OpenID
        String openId = wxMsgBean.getFromUserName();
        //公众号ID
        String appID = wxMsgBean.getToUserName();
        //消息类型
        String msgType = wxMsgBean.getMsgType();
        UserLog userLog = new UserLog();
        userLog.setOpenId(openId);
        userLog.setCreatTime(new Date());
        switch (msgType){
            //获取地址的，然后发送当前地址的信息
            case "event":
                //这个是设置的点卡聊天节目界面就进行推送，可以自行修改
                String event = wxMsgBean.getEvent();
                if (event.equals("LOCATION")){
                    //经度
                    String Longitude = wxMsgBean.getLongitude();
                    //维度
                    String Latitude = wxMsgBean.getLatitude();
                    //地理位置精度
                    String Precision = wxMsgBean.getPrecision();
                    //进行赋值
                    mInfo.put("Latitude",Latitude);
                    mInfo.put("Longitude",Longitude);
                    mmInfo.put(openId,mInfo);
                    //不自动发送地址信息了，打印一下经纬度，可以自行存储数据库
                    logger.info("用户openId可以去官网进行查看:"+openId+",经度:"+Longitude+",维度:"+Latitude+",精度:"+Precision);
                    //添加到数据库，这里是测试，处理id全都可以为空，也不进行处理异常，报错什么的
                    UserArea userArea = new UserArea();
                    userArea.setOpenId(openId);
                    userArea.setLongitude(Longitude);
                    userArea.setLatitude(Latitude);
                    userArea.setPrecision1(Precision);
                    userArea.setCreateTime(new Date());
                    userAreaMapper.insertSelective(userArea);
                    userLog.setType(0);
                    userLog.setRemark("用户已开启定位：");
                    userLogMapper.insertSelective(userLog);
                    return "success";
                }
                break;
            case "text":
                String content = wxMsgBean.getContent();
                userLog.setType(1);
                userLog.setRemark("用户发送消息：");
                userLog.setText(content);
                userLogMapper.insertSelective(userLog);
                switch (content){
                    case "天气":
                    case "tq":
                        //获取当前用户信息，第一次使用没有，之后就会有
                        if (!mmInfo.toString().equals("{}") && mmInfo.toString().contains(openId+"={")){
                            mInfo = mmInfo.get(openId);
                            //集合不为空
                            if (!mInfo.toString().equals("{}")){
                                //数据不为空
                                if (!StringUtils.isBlank(mInfo.get("Latitude")) && !StringUtils.isBlank(mInfo.get("Longitude"))){
                                    Map<String,String> map = addrUtils.getAddr(mInfo.get("Longitude"),mInfo.get("Latitude"));
                                    wxUtils.pushWeather(openId,map.get("province"),map.get("city"));
                                    mmInfo.put(openId,mInfo);
                                }
                            }
                        }else {
                            //这里没有定位默认使用
                            wxUtils.pushWeather(openId,"山东省","临沂市(未开启定位，默认使用)");
                        }
                        break;
                    case "日期":
                    case "rq":
                    case "纪念日":
                    case "jnr":
                        wxUtils.pushDate(openId);
                        break;
                    default:
                        //拼一下要返回的信息对象
                        return WxUtils.reply(appID,openId,content);
                }
                break;
            default:
                return WxUtils.reply(appID,openId,"等着开发吧");
        }
        return "success";
    }

    //发送给yml添加的全部用户
    @Override
    public void wxPushHello() {
        List<String> openIds = wxMpProperties.getPushUser();
        for (int i = 0; i < openIds.size(); i++) {
            wxUtils.pushTemplate(openIds.get(i));
        }
    }

    //纪念日这样的
    @Override
    public void wxPushDate() {
        List<String> openIds = wxMpProperties.getPushUser();
        for (int i = 0; i < openIds.size(); i++) {
            wxUtils.pushDate(openIds.get(i));
        }
    }


    @Override
    public void wxPushHost() {
        List<String> openIds = wxMpProperties.getPushUser();
        UserLog userLog = new UserLog();
        userLog.setCreatTime(new Date());
        userLog.setType(0);
        userLog.setRemark("给用户进行定时推送消息");
        for (int i = 0; i < openIds.size(); i++) {
            wxUtils.pushTemplate1(openIds.get(i));
            userLog.setOpenId(openIds.get(i));
            userLogMapper.insertSelective(userLog);
        }
    }

    @Override
    public void test() {
        logger.info(TimeUtils.longToDate(new Date().getTime())+"==》测试调用");
    }

    @Override
    public void qyWxRobot() {
        QyWxRobot robot = new QyWxRobot();
        //位置放到这里写是考虑有多个机器人的情况
        robot.setWebhookAddress(wxMpProperties.getWebhook());
        robot.setMsgType("markdown");
        qyWxUtils.toSend(robot);
    }


}

